#include "data_process.h"
#include <stdio.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>  // 添加这个头文件

#define MAX_EXIT_NUM 64

// 保存读取的系统配置信息 文本信息 "./config/sys-conf.json"
SYSTEM_INFO *system_info = NULL;
PAGE_INFO   *page_info = NULL;
SYSTEM_INFO system_info_;

// 保存读取的页面配置 文本信息
char ProjectName[50];  // Project Name: 水果分选 - 赣南脐橙
char BtnClean[50];     // Btn Clean: 清除
char BtnApply[50];     // Btn Apply: 应用
char exitGradeText[50]; // Work Info - exit Grade Text: 出口等级
char BoxedPercent[50]; // exit Status - Boxed Percent: 装箱\n进度
char BoxedCnt[50];     // 装箱\n个数
char FruitingEfficiency[50]; // 出果\n效率

char SETTING[10];//设置
char CHANGE_PRINT_MODE[30];//设置
char language_text[20];// 语言
char SYSSETTING[20];//系统设置
char Exit_cnt_text[20];// 出口个数
char Exit_printer_text[20];// 打印
char print_left_text[20];// 打印 左
char print_right_text[20];// 打印 右
char NETWORKSETTING[20];// 网络设置
char SYSINFO[20];//系统信息
char SYSSTART[20];// 重启系统
char CONNECT[20]; //wifi连接
char DISCONNECT[20];// wifi断开连接
char APPLY[10];// 应用
char BACK[10];// 返回

// 存储出口信息
exit_INFO exit1;
exit_INFO exit2;

// 定义结构体
typedef struct {
    char *FruitName;
    char *ExitName;
    float BoxPercent;
    float Box;
    char *BoxUnit;
    float ExitPercent;
    char **Grades;
    int numGrades;
} FruitInfo;

// 释放 FruitInfo 结构体及其内部指针的内存
static void freeFruitInfo(FruitInfo *info) {
    if (info == NULL) {
        return;
    }
    if (info->FruitName!= NULL) {
        free(info->FruitName);
    }
    if (info->ExitName!= NULL) {
        free(info->ExitName);
    }
    if (info->BoxUnit!= NULL) {
        free(info->BoxUnit);
    }
    if (info->Grades!= NULL) {
        for (int i = 0; i < info->numGrades; i++) {
            if (info->Grades[i]!= NULL) {
                free(info->Grades[i]);
            }
        }
        free(info->Grades);
    }
    free(info);
}

// 解析 ExitInfos 数组中的一个元素为 FruitInfo 结构体
static FruitInfo *parseExitInfo(cJSON *exitInfo) {
    FruitInfo *info = (FruitInfo *)malloc(sizeof(FruitInfo));
    if (info == NULL) {
        return NULL;
    }
    cJSON *fruitName = cJSON_GetObjectItemCaseSensitive(exitInfo, "FruitName");
    if (fruitName!= NULL && cJSON_IsString(fruitName)) {
        info->FruitName = strdup(fruitName->valuestring);
    } else {
        info->FruitName = NULL;
    }
    cJSON *exitName = cJSON_GetObjectItemCaseSensitive(exitInfo, "ExitName");
    if (exitName!= NULL && cJSON_IsString(exitName)) {
        info->ExitName = strdup(exitName->valuestring);
    } else {
        info->ExitName = NULL;
    }
    cJSON *boxPercent = cJSON_GetObjectItemCaseSensitive(exitInfo, "BoxPercent");
    if (boxPercent!= NULL && cJSON_IsNumber(boxPercent)) {
        info->BoxPercent = (float)boxPercent->valuedouble;
    } else {
        info->BoxPercent = 0.0;
    }
    cJSON *box = cJSON_GetObjectItemCaseSensitive(exitInfo, "Box");
    if (box!= NULL && cJSON_IsNumber(box)) {
        info->Box = (float)box->valuedouble;
    } else {
        info->Box = 0.0;
    }
    cJSON *boxUnit = cJSON_GetObjectItemCaseSensitive(exitInfo, "BoxUnit");
    if (boxUnit!= NULL && cJSON_IsString(boxUnit)) {
        info->BoxUnit = strdup(boxUnit->valuestring);
    } else {
        info->BoxUnit = NULL;
    }
    cJSON *exitPercent = cJSON_GetObjectItemCaseSensitive(exitInfo, "ExitPercent");
    if (exitPercent!= NULL && cJSON_IsNumber(exitPercent)) {
        info->ExitPercent = (float)exitPercent->valuedouble;
    } else {
        info->ExitPercent = 0.0;
    }
    cJSON *grades = cJSON_GetObjectItemCaseSensitive(exitInfo, "Grades");
    if (grades!= NULL && cJSON_IsArray(grades)) {
        int numGrades = cJSON_GetArraySize(grades);
        info->numGrades = numGrades;
        info->Grades = (char **)malloc(sizeof(char *) * numGrades);
        if (info->Grades == NULL) {
            freeFruitInfo(info);
            return NULL;
        }
        for (int i = 0; i < numGrades; i++) {
            cJSON *grade = cJSON_GetArrayItem(grades, i);
            if (grade!= NULL && cJSON_IsString(grade)) {
                info->Grades[i] = strdup(grade->valuestring);
                if (info->Grades[i] == NULL) {
                    freeFruitInfo(info);
                    return NULL;
                }
            } else {
                info->Grades[i] = NULL;
            }
        }
    } else {
        info->Grades = NULL;
        info->numGrades = 0;
    }
    return info;
}

// 解析整个 JSON 字符串
int exit_info_JSON(const char *jsonString) 
{
    cJSON *root = cJSON_Parse(jsonString);
    if (root == NULL) {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr!= NULL) {
            // fprintf(stderr, "Error before: %s\n", error_ptr);
        }
        return -2;
    }
    cJSON *cmd = cJSON_GetObjectItemCaseSensitive(root, "Cmd");
    if (cmd!= NULL && cJSON_IsNumber(cmd)) {
        int cmdValue = (int)cmd->valueint;
        reemoon_ignore ("Cmd: %d\n", cmdValue);
    }
    else
    {
        return -2;
    }
    cJSON *message = cJSON_GetObjectItemCaseSensitive(root, "Message");
    if (message!= NULL && cJSON_IsString(message)) {
        cJSON *messageJson = cJSON_Parse(message->valuestring);
        if (messageJson == NULL) {
            const char *error_ptr = cJSON_GetErrorPtr();
            if (error_ptr!= NULL) {
                fprintf(stderr, "Error parsing Message: %s\n", error_ptr);
            }
            cJSON_Delete(root);
            return -2;
        }
        cJSON *exitInfos = cJSON_GetObjectItemCaseSensitive(messageJson, "ExitInfos");
        if (exitInfos!= NULL && cJSON_IsArray(exitInfos)) {
            int arraySize = cJSON_GetArraySize(exitInfos);
            reemoon_clean_exit_grade();
            cJSON *exitInfo = cJSON_GetArrayItem(exitInfos, reemoon_get_exit_id(1)-1);
            if (exitInfo!= NULL) 
            {
                FruitInfo *info = parseExitInfo(exitInfo);
                if (info!= NULL) 
                {
                    sprintf (exit1.fruitname, "%s", (info->FruitName!= NULL)? info->FruitName : "fruit");
                    exit1.boxed_percent = info->BoxPercent;
                    exit1.box_cnt = info->Box;
                    exit1.exit_percent = info->ExitPercent;
                    char *p = exit1.exit_grade;
                    for (int j = 0; j < info->numGrades; j++) 
                    {
                        sprintf (p, "%s\n", (info->Grades[j]!= NULL)? info->Grades[j] : "");
                        p += strlen(info->Grades[j])+1;
                    }
                    // reemoon_ignore ("%s\n", exit1.exit_grade); 
                    // reemoon_ignore ("FruitName: %s\n", (info->FruitName!= NULL)? info->FruitName : "fruit");
                    // reemoon_ignore ("ExitName: %s\n", (info->ExitName!= NULL)? info->ExitName : "NULL");
                    // reemoon_ignore ("BoxPercent: %0.1f\n", exit1.boxed_percent);
                    // reemoon_ignore ("Box: %0.1f\n", exit1.box_cnt);
                    // reemoon_ignore ("BoxUnit: %s\n", (info->BoxUnit!= NULL)? info->BoxUnit : "NULL");
                    // reemoon_ignore ("ExitPercent: %0.1f\n", exit1.exit_percent);
                    freeFruitInfo(info);
                }
            }
            if (system_info->exit_cnt == 2)
            {
                exitInfo = cJSON_GetArrayItem(exitInfos, reemoon_get_exit_id(2)-1);
                if (exitInfo!= NULL) 
                {
                    FruitInfo *info = parseExitInfo(exitInfo);
                    if (info!= NULL) 
                    {
                        sprintf (exit2.fruitname, "%s", (info->FruitName!= NULL)? info->FruitName : "fruit");
                        exit2.boxed_percent = info->BoxPercent;
                        exit2.box_cnt = info->Box;
                        exit2.exit_percent = info->ExitPercent;
                        char *p = exit2.exit_grade;
                        for (int j = 0; j < info->numGrades; j++) 
                        {
                            sprintf (p, "%s\n", (info->Grades[j]!= NULL)? info->Grades[j] : "");
                            p += strlen(info->Grades[j])+1;
                        }
                        freeFruitInfo(info);
                    }
                }
            }
            #if 0
            for (int i = 0; i < arraySize; i++) {
                cJSON *exitInfo = cJSON_GetArrayItem(exitInfos, i);
                if (exitInfo!= NULL) {
                    FruitInfo *info = parseExitInfo(exitInfo);
                    if (info!= NULL) {
                        // 在这里可以对解析出来的 info 进行处理，例如打印或存储
                        // 示例：打印信息
                        reemoon_ignore("FruitName: %s\n", (info->FruitName!= NULL)? info->FruitName : "NULL");
                        reemoon_ignore("ExitName: %s\n", (info->ExitName!= NULL)? info->ExitName : "NULL");
                        reemoon_ignore("BoxPercent: %f\n", info->BoxPercent);
                        reemoon_ignore("Box: %f\n", info->Box);
                        reemoon_ignore("BoxUnit: %s\n", (info->BoxUnit!= NULL)? info->BoxUnit : "NULL");
                        reemoon_ignore("ExitPercent: %f\n", info->ExitPercent);
                        for (int j = 0; j < info->numGrades; j++) {
                            reemoon_ignore("Grade %d: %s\n", j, (info->Grades[j]!= NULL)? info->Grades[j] : "NULL");
                        }
                        // 释放 FruitInfo 结构体的内存
                        freeFruitInfo(info);
                    }
                }
            }
            #endif
        }
        cJSON_Delete(messageJson);
    }
    cJSON_Delete(root);
    return 0;
}

void parse_sysconf_JSON(const char *jsonStr) 
{
    cJSON *root = cJSON_Parse(jsonStr);
    if (root == NULL) {
        reemoon_error ("Failed to parse JSON string.\n");
        return;
    }
    // 获取各个键值对的值
    cJSON *project_ = cJSON_GetObjectItem(root, "project");
    cJSON *link_mode_ = cJSON_GetObjectItem(root, "link-mode");
    cJSON *server_ip_ = cJSON_GetObjectItem(root, "server-ip");
    cJSON *server_port_ = cJSON_GetObjectItem(root, "server-port");
    cJSON *mqtt_topic_ = cJSON_GetObjectItem(root, "mqtt-topic");
    cJSON *default_font_ = cJSON_GetObjectItem(root, "default-font");
    cJSON *rabbitmq_username_ = cJSON_GetObjectItem(root, "rabbitmq-username");
    cJSON *rabbitmq_password_ = cJSON_GetObjectItem(root, "rabbitmq-password");
    cJSON *rabbitmq_fanout_exchangename_ = cJSON_GetObjectItem(root, "rabbitmq-fanout-exchangename");
    cJSON *rabbitmq_simple_queuename_ = cJSON_GetObjectItem(root, "rabbitmq-simple-queuename");

    cJSON *version_ = cJSON_GetObjectItem(root, "version-info");
    cJSON *language_ = cJSON_GetObjectItem(root, "language");
    cJSON *exit_cnt_ = cJSON_GetObjectItem(root, "exit-cnt");
    cJSON *author_ = cJSON_GetObjectItem(root, "author");

    if (project_!= NULL) {
        reemoon_ignore ("Project: %s\n", project_->valuestring);
    }
    if (server_ip_!= NULL) {
        memcpy(system_info->server_ip, server_ip_->valuestring, strlen(server_ip_->valuestring));
        reemoon_ignore ("Server IP: %s\n", server_ip_->valuestring);
    }
    if (server_port_!= NULL) {
        system_info->server_port = server_port_->valueint;
        reemoon_ignore ("Server Port: %d\n", server_port_->valueint);
    }
    #if MQTT_ENABLE
    if (mqtt_topic_!= NULL) {
        memcpy(system_info->mqtt_topic, mqtt_topic_->valuestring, strlen(mqtt_topic_->valuestring));
        reemoon_ignore ("Mqtt topic: %s\n", mqtt_topic_->valuestring);
    }
    #endif
    #if RABBITMQ_ENABLE
    if (rabbitmq_username_!= NULL) {
        memcpy(system_info->rabbitmq_username, rabbitmq_username_->valuestring, strlen(rabbitmq_username_->valuestring));
        reemoon_ignore ("rabbitmq username: %s\n", rabbitmq_username_->valuestring);
    }
    if (rabbitmq_password_!= NULL) {
        memcpy(system_info->rabbitmq_password, rabbitmq_password_->valuestring, strlen(rabbitmq_password_->valuestring));
        reemoon_ignore ("rabbitmq username: %s\n", rabbitmq_password_->valuestring);
    }
    if (rabbitmq_fanout_exchangename_!= NULL) {
        memcpy(system_info->rabbitmq_fanout_exchangename, rabbitmq_fanout_exchangename_->valuestring, strlen(rabbitmq_fanout_exchangename_->valuestring));
        reemoon_ignore ("rabbitmq username: %s\n", rabbitmq_fanout_exchangename_->valuestring);
    }
    if (rabbitmq_simple_queuename_!= NULL) {
        memcpy(system_info->rabbitmq_simple_queuename, rabbitmq_simple_queuename_->valuestring, strlen(rabbitmq_simple_queuename_->valuestring));
        reemoon_ignore ("rabbitmq username: %s\n", rabbitmq_simple_queuename_->valuestring);
    }
    #endif
    if (default_font_!= NULL) {
        if (strstr(default_font_->valuestring, "small"))
        {
            system_info->font = FT_SMALL;
        }
        else if (strstr(default_font_->valuestring, "medium"))
        {
            system_info->font = FT_MEDIUM;
        }
        else if (strstr(default_font_->valuestring, "large"))
        {
            system_info->font = FT_LARGE;
        }
        reemoon_ignore ("Default Font: %s\n", default_font_->valuestring);
    }
    if (version_!= NULL) {
        int size = strlen(version_->valuestring);
        memcpy(system_info->version, version_->valuestring, size);
        system_info->version[size] = '\0';
        reemoon_ignore ("Version: %s\n", system_info->version);
    }
    if (language_!= NULL) {
        if (strstr(language_->valuestring, "Chinese"))
        {
            system_info->language = LANGUAGE_CN;
        }
        else if (strstr(language_->valuestring, "English"))
        {
            system_info->language = LANGUAGE_EN;
        }
        reemoon_ignore ("Language: %s\n", language_->valuestring);
    }
    if (exit_cnt_ != NULL)
    {
        system_info->exit_cnt = exit_cnt_->valueint;
        reemoon_ignore ("exit cnt: %d\n", exit_cnt_->valueint);
    }
    if (author_!= NULL) {
        reemoon_ignore ("Author: %s\n", author_->valuestring);
    }
    cJSON_Delete(root); // 释放资源
}

// 解析 JSON 数据的函数
void parse_ui_JSON(const char *jsonStr) 
{
    cJSON *root = cJSON_Parse(jsonStr);
    if (root == NULL) {
        reemoon_error ("Failed to parse JSON string.\n");
        return;
    }

    // 获取 "project-name" 的值
    cJSON *ProjectName_ = cJSON_GetObjectItem(root, "project-name");
    if (ProjectName_!= NULL) {
        memcpy(ProjectName, ProjectName_->valuestring, strlen(ProjectName_->valuestring));
        reemoon_ignore ("ProjectName: %s\n", ProjectName_->valuestring);
    }

    // 获取 "exit-conf" 对象及其子项的值
    cJSON *exitConf_ = cJSON_GetObjectItem(root, "exit-conf");
    if (exitConf_!= NULL) {
        cJSON *BtnClean_ = cJSON_GetObjectItem(exitConf_, "btn-clean");
        if (BtnClean_!= NULL) {
            memcpy(BtnClean, BtnClean_->valuestring, strlen(BtnClean_->valuestring));
            reemoon_ignore ("exitConf-BtnClean: %s\n", BtnClean_->valuestring);
        }
    }

    // 获取 "work-info" 对象及其子项的值
    cJSON *workInfo_ = cJSON_GetObjectItem(root, "work-info");
    if (workInfo_!= NULL) {
        cJSON *exitGradeText_ = cJSON_GetObjectItem(workInfo_, "exit-grade-text");
        if (exitGradeText_!= NULL) {
            memcpy(exitGradeText, exitGradeText_->valuestring, strlen(exitGradeText_->valuestring));
            reemoon_ignore ("WorkInfo-exitGrade Text: %s\n", exitGradeText_->valuestring);
        }
        cJSON * change_print_mode = cJSON_GetObjectItem(workInfo_, "change-print-mode");
        if (change_print_mode != NULL)
        {
            memcpy (CHANGE_PRINT_MODE, change_print_mode->valuestring, strlen(change_print_mode->valuestring));
            reemoon_ignore ("Change print mode Text: %s\n", change_print_mode->valuestring);
        }
    }
    // 获取 "exit-status" 对象及其子项的值
    cJSON *exitStatus_ = cJSON_GetObjectItem(root, "exit-status");
    if (exitStatus_!= NULL) {
        cJSON *BoxedPercent_ = cJSON_GetObjectItem(exitStatus_, "boxed-percent");
        if (BoxedPercent_!= NULL) {
            memcpy(BoxedPercent, BoxedPercent_->valuestring, strlen(BoxedPercent_->valuestring));
            reemoon_ignore("exitStatus-Boxed Percent: %s\n", BoxedPercent_->valuestring);
        }
        cJSON *BoxedCnt_ = cJSON_GetObjectItem(exitStatus_, "boxed-cnt");
        if (BoxedCnt_!= NULL) {
            memcpy(BoxedCnt, BoxedCnt_->valuestring, strlen(BoxedCnt_->valuestring));
            reemoon_ignore("exitStatus-BoxedCnt: %s\n", BoxedCnt_->valuestring);
        }
        cJSON *FruitingEfficiency_ = cJSON_GetObjectItem(exitStatus_, "Fruiting-efficiency");
        if (FruitingEfficiency_!= NULL) {
            memcpy(FruitingEfficiency, FruitingEfficiency_->valuestring, strlen(FruitingEfficiency_->valuestring));
            reemoon_ignore("exitStatus-FruitingEfficiency: %s\n", FruitingEfficiency_->valuestring);
        }
    }
    cJSON *Setting = cJSON_GetObjectItem(root,"setting");
    memcpy(SETTING, Setting->valuestring, sizeof(SETTING));

    cJSON *Language_text = cJSON_GetObjectItem(root,"language");
    memcpy(language_text, Language_text->valuestring, sizeof(language_text));
    
    cJSON *exit_cnt_text = cJSON_GetObjectItem(root,"exit-cnt-text");
    memcpy(Exit_cnt_text, exit_cnt_text->valuestring, sizeof(Exit_cnt_text));

    cJSON *Print = cJSON_GetObjectItem(root, "print");
    memcpy(Exit_printer_text, Print->valuestring, sizeof(Exit_printer_text));

    cJSON *Print_left = cJSON_GetObjectItem(root, "print-left");
    memcpy(print_left_text, Print_left->valuestring, sizeof(print_left_text));
    
    cJSON *Print_right = cJSON_GetObjectItem(root, "print-right");
    memcpy(print_right_text, Print_right->valuestring, sizeof(print_right_text));

    cJSON *System_Setting = cJSON_GetObjectItem(root,"sys-setting");
    memcpy(SYSSETTING, System_Setting->valuestring, sizeof(SYSSETTING));

    cJSON *Network_Setting = cJSON_GetObjectItem(root,"network-setting");
    memcpy(NETWORKSETTING, Network_Setting->valuestring, sizeof(NETWORKSETTING));

    cJSON *System_info = cJSON_GetObjectItem(root,"sys-info");
    memcpy(SYSINFO, System_info->valuestring, sizeof(SYSINFO));

    cJSON *System_restart = cJSON_GetObjectItem(root,"sys-restart");
    memcpy(SYSSTART, System_restart->valuestring, sizeof(SYSSTART));

    cJSON *CONNECT_ = cJSON_GetObjectItem(root,"connect");
    memcpy(CONNECT, CONNECT_->valuestring, sizeof(CONNECT));

    cJSON *DISCONNECT_ = cJSON_GetObjectItem(root,"disconnect");
    memcpy(DISCONNECT, DISCONNECT_->valuestring, sizeof(DISCONNECT));

    cJSON *APPLY_ = cJSON_GetObjectItem(root,"apply");
    memcpy(APPLY, APPLY_->valuestring, sizeof(APPLY));

    cJSON *BACK_ = cJSON_GetObjectItem(root,"back");
    memcpy(BACK, BACK_->valuestring, sizeof(BACK));

    cJSON_Delete(root); // 释放资源
}

// 修改 JSON 数据中 server-ip 和 server-port 的函数
int set_server_info(const char *newServerIp, int newServerPort) 
{
    int data_size = 1024 * sizeof(char);
    char *data_buff = malloc(data_size);
    int size = reemoon_read_file(SYSTEM_CONFIG_FILE, data_buff, data_size) ;
    if (size<=0)
    {
        free (data_buff);
        return -1;
    }
    cJSON *root = cJSON_Parse(data_buff);
    if (root == NULL) {
        reemoon_error("Failed to parse JSON string.\n");
        free (data_buff);
        return -1;
    }

    // 获取 server-ip 和 server-port 的 cJSON 对象
    cJSON *server_ip_ = cJSON_GetObjectItem(root, "server-ip");
    cJSON *server_port_ = cJSON_GetObjectItem(root, "server-port");

    // 修改 server-ip 的值
    if (server_ip_ != NULL) {
        cJSON_SetValuestring(server_ip_, newServerIp);
        memset (system_info->server_ip, 0x00, sizeof(system_info->server_ip));
        memcpy (system_info->server_ip, newServerIp, strlen (newServerIp));
    }
    // 修改 server-port 的值
    if (server_port_ != NULL) {
        cJSON_SetNumberValue(server_port_, newServerPort);
        system_info->server_port = newServerPort;
    }

    // 生成修改后的 JSON 字符串
    char *newJsonStr = cJSON_Print(root);
    reemoon_write_file(SYSTEM_CONFIG_FILE, newJsonStr, strlen(newJsonStr)) ;

    // 释放解析得到的 cJSON 对象
    cJSON_Delete(root);
    free (data_buff);

    return 0;
}

// 修改 JSON 数据中 language 的函数
int set_language(const char *newLanguage) 
{
    int data_size = 1024 * sizeof(char);
    char *data_buff = malloc(data_size);
    int size = reemoon_read_file(SYSTEM_CONFIG_FILE, data_buff, data_size) ;
    if (size<=0)
    {
        free (data_buff);
        return -1;
    }
    cJSON *root = cJSON_Parse(data_buff);
    if (root == NULL) {
        reemoon_error("Failed to parse JSON string.\n");
        free (data_buff);
        return -1;
    }

    cJSON *language_ = cJSON_GetObjectItem(root, "language");
    if (strstr(newLanguage, "Chinese"))
    {
        system_info->language = LANGUAGE_CN;
    }
    else if (strstr(newLanguage, "English"))
    {
        system_info->language = LANGUAGE_EN;
    }
    reemoon_ignore ("Language: %s\n", language_->valuestring);

    if (language_ != NULL) {
        cJSON_SetValuestring(language_, newLanguage);
    }

    // 生成修改后的 JSON 字符串
    char *newJsonStr = cJSON_Print(root);
    reemoon_write_file(SYSTEM_CONFIG_FILE, newJsonStr, strlen(newJsonStr)) ;

    // 释放解析得到的 cJSON 对象
    cJSON_Delete(root);
    free (data_buff);

    return 0;
}
// 修改 JSON 数据中 link mode 的函数
int set_link_mode(const char *newMode) 
{
    int data_size = 1024 * sizeof(char);
    char *data_buff = malloc(data_size);
    int size = reemoon_read_file(SYSTEM_CONFIG_FILE, data_buff, data_size) ;
    if (size<=0)
    {
        free (data_buff);
        return -1;
    }
    cJSON *root = cJSON_Parse(data_buff);
    if (root == NULL) {
        reemoon_error("Failed to parse JSON string.\n");
        free (data_buff);
        return -1;
    }

    // 生成修改后的 JSON 字符串
    char *newJsonStr = cJSON_Print(root);
    reemoon_write_file(SYSTEM_CONFIG_FILE, newJsonStr, strlen(newJsonStr)) ;

    // 释放解析得到的 cJSON 对象
    cJSON_Delete(root);
    free (data_buff);

    return 0;
}

int set_exit_cnt(int newCnt) 
{
    if (newCnt <= 0)
        return -1;
    int data_size = 1024 * sizeof(char);
    char *data_buff = malloc(data_size);
    int size = reemoon_read_file(SYSTEM_CONFIG_FILE, data_buff, data_size) ;
    if (size<=0)
    {
        free (data_buff);
        return -1;
    }
    cJSON *root = cJSON_Parse(data_buff);
    if (root == NULL) {
        reemoon_error("Failed to parse JSON string.\n");
        free (data_buff);
        return -1;
    }
    cJSON *exit_cnt_ = cJSON_GetObjectItem(root, "exit-cnt");

    // 修改 exit_cnt 的值
    if (exit_cnt_ != NULL) {
        cJSON_SetNumberValue(exit_cnt_, newCnt);
        system_info->exit_cnt = newCnt;
    }

    // 生成修改后的 JSON 字符串
    char *newJsonStr = cJSON_Print(root);
    reemoon_write_file(SYSTEM_CONFIG_FILE, newJsonStr, strlen(newJsonStr)) ;

    // 释放解析得到的 cJSON 对象
    cJSON_Delete(root);
    free (data_buff);

    return 0;
}

char *get_system_local_ip_info(void)
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s, len=0;
    char host[NI_MAXHOST];
    memset(Interface_name, 0, sizeof(Interface_name));
    char *p = &Interface_name[0];

    Interface_cnt = 0;

    if (getifaddrs(&ifaddr) == -1) {
        reemoon_error("getifaddrs\n");
        return NULL;
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr == NULL)
            continue;

        family = ifa->ifa_addr->sa_family;

        if (family == AF_INET) { // IPv4
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
                            host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", strerror(s));
                continue;
            }
            if (strstr(ifa->ifa_name, "eth") || strstr(ifa->ifa_name, "wlan"))
            {
                sprintf (p, "%s", ifa->ifa_name);
                len = strlen(ifa->ifa_name);
                *(p+len) = '\n';
                p += len+1;
                sprintf (Interface_address[Interface_cnt++], "%s", host);
                reemoon_ignore ("Interface_cnt: %d, Interface: %s, IPv4 Address: %s\n",Interface_cnt,  ifa->ifa_name, host);
            }
        }
    }
    len = strlen(Interface_name);
    *(Interface_name+len-1) = '\0';
    
    reemoon_ignore ("Interface_name: %s\n", Interface_name);

    freeifaddrs(ifaddr);
}


#define MAX_LINE_LENGTH 256
#define MAX_SSID_LENGTH 64
#define MAX_PASSWORD_LENGTH 64
// 提取 SSID 和密码的函数
int get_wifi_info(const char *file_path, char *ssid, char *password) 
{
    FILE *file = fopen(file_path, "r");
    if (file == NULL) {
        reemoon_error("Failed to open file\n");
        return -1;
    }
    char line[MAX_LINE_LENGTH];
    int in_network_block = 0;
    while (fgets(line, MAX_LINE_LENGTH, file) != NULL) {
        if (strstr(line, "network={") != NULL) {
            in_network_block = 1;
            continue;
        }
        if (strstr(line, "}") != NULL) {
            in_network_block = 0;
            continue;
        }
        if (in_network_block) {
            if (strstr(line, "ssid=") != NULL) {
                char *start = strchr(line, '"');
                if (start != NULL) {
                    start++;
                    char *end = strchr(start, '"');
                    if (end != NULL) {
                        strncpy(ssid, start, end - start);
                        ssid[end - start] = '\0';
                    }
                }
            } else if (strstr(line, "psk=") != NULL) {
                char *start = strchr(line, '"');
                if (start != NULL) {
                    start++;
                    char *end = strchr(start, '"');
                    if (end != NULL) {
                        strncpy(password, start, end - start);
                        password[end - start] = '\0';
                    }
                }
            }
        }
    }
    fclose(file);
    if (strlen(ssid) == 0 || strlen(password) == 0) {
        return -1;
    }
    return 0;
}

#define MAX_FILE_PATH_LENGTH 256
// 读取并更新 wpa_supplicant.conf 文件中的 SSID 和密码
int set_wifi_info(const char *file_path, const char *new_ssid, const char *new_password) 
{
    FILE *input_file = fopen(file_path, "r");
    if (input_file == NULL) {
        reemoon_error("Failed to open file for reading, %s\n", file_path);
        return -1;
    }
    char temp_file_path[MAX_FILE_PATH_LENGTH];
    snprintf(temp_file_path, sizeof(temp_file_path), "%s.tmp", file_path);
    FILE *output_file = fopen(temp_file_path, "w");
    if (output_file == NULL) {
        reemoon_error("Failed to open temporary file for writing\n");
        fclose(input_file);
        return -1;
    }
    char line[MAX_LINE_LENGTH];
    int in_network_block = 0;
    while (fgets(line, MAX_LINE_LENGTH, input_file) != NULL) {
        if (strstr(line, "network={") != NULL) {
            in_network_block = 1;
            fputs(line, output_file);
            continue;
        }
        if (strstr(line, "}") != NULL) {
            in_network_block = 0;
            fputs(line, output_file);
            continue;
        }
        if (in_network_block) {
            if (strstr(line, "ssid=") != NULL) {
                fprintf(output_file, "    ssid=\"%s\"\n", new_ssid);
            } else if (strstr(line, "psk=") != NULL) {
                fprintf(output_file, "    psk=\"%s\"\n", new_password);
            } else {
                fputs(line, output_file);
            }
        } else {
            fputs(line, output_file);
        }
    }
    fclose(input_file);
    fclose(output_file);
    // 用临时文件替换原文件
    if (rename(temp_file_path, file_path) != 0) {
        reemoon_error("Failed to rename temporary file\n");
        return -1;
    }
    return 0;
}
